package com.xexun.gpstracker.my.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.base.BaseActivity;
import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenu;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuCreator;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuItem;
import com.xexun.gpstracker.fix.swipemenu.SwipeMenuListView;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.my.adapter.AlarmAdapter;
import com.xexun.gpstracker.pojo.AlarmEntity;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.util.*;
import com.xexun.gpstracker.vo.Session;

/**
 * 生活助手页面
 *
 * @author huangfei
 */
public class AlarmActivity extends BaseActivity {
    private ImageButton backButton, addButton;
    private SwipeMenuListView listView;
    private TextView alarmPrompt;

    private List<AlarmEntity> entityList = new ArrayList<AlarmEntity>();
    private AlarmAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);

        TextView titleTV = (TextView) findViewById(R.id.titleNameTV);
        titleTV.setText(getString(R.string.setup_alarm) + "-" + Session.getInstance().getSetupDevice().getName());
        backButton = (ImageButton) findViewById(R.id.backBtn);
        addButton = (ImageButton) findViewById(R.id.addBtn);
        alarmPrompt = (TextView) findViewById(R.id.alarm_prompt);

        backButton.setOnClickListener(clickListener);
        addButton.setOnClickListener(clickListener);

        listView = (SwipeMenuListView) findViewById(R.id.listView1);
        mAdapter = new AlarmAdapter(AlarmActivity.this, entityList);
        listView.setAdapter(mAdapter);
        listView.setOnMenuItemClickListener(onMenuItemClickListener);
        listView.setMenuCreator(new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem updateItem = new SwipeMenuItem(AppContext.getContext());
                updateItem.setBackground(new ColorDrawable(Color.parseColor("#FF924E")));
                updateItem.setWidth(Utils.dp2px(AppContext.getContext(), 80f));
                updateItem.setTitle(R.string.edit);
                updateItem.setTitleSize(18);
                updateItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(updateItem);

                SwipeMenuItem delItem = new SwipeMenuItem(AlarmActivity.this);
                delItem.setBackground(R.color.red);
                delItem.setWidth(Utils.dp2px(AlarmActivity.this, 80f));
                delItem.setTitle(R.string.delete);
                delItem.setTitleSize(18);
                delItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(delItem);
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                listView.smoothOpenMenu(position);
            }
        });
    }

    private SwipeMenuListView.OnMenuItemClickListener onMenuItemClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
            switch (index) {
                case 0:
                    Intent intent = new Intent(AlarmActivity.this, AddAlarmActivity.class);
                    intent.putExtra("alarm", entityList.get(position));
                    AlarmActivity.this.startActivity(intent);
                    break;
                case 1:
                    new AlertDialog.Builder(AlarmActivity.this)
                            .setTitle(R.string.notice)
                            .setMessage(String.format(getString(R.string.confirm_msg), getString(R.string.delete_alarm)))
                            .setPositiveButton(R.string.yes, menuDialogListener.with(position))
                            .setNegativeButton(R.string.no, null)
                            .show();
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    MenuDialogListener menuDialogListener = new MenuDialogListener();

    private class MenuDialogListener implements DialogInterface.OnClickListener {
        private int position;

        public MenuDialogListener with(int position) {
            this.position = position;
            return this;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onStart() {
                    WizardAlertDialog.getInstance().showProgressDialog("", AlarmActivity.this);
                }

                @Override
                public void onFinish() {
                    WizardAlertDialog.getInstance().closeProgressDialog();
                }

                @Override
                public void onSuccess(ResponseData obj) {
                    if (obj.getRetcode() == 1) {
                        CommUtil.showMsgShort(getString(R.string.delete_success));
                        getData();
                    } else {
                        CommUtil.showMsgShort(getString(R.string.delete_failed));
                    }
                }

                @Override
                public void onFailure(String message) {
                }
            };
            try {
                JSONArray json = new JSONArray();
                json.put(entityList.get(position).getId());
                JSONObject data = new JSONObject();
                data.put("ids", json);
                HttpUtil.post(CommonRestPath.alarmDelete(), data, new JsonHttpResponseHelper(callback).getHandler());
            } catch (Exception e) {
                Log.e(AlarmActivity.class.getName(), "删除失败", e);
            }
        }
    }

    /**
     * 点击事件
     */
    private OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.backBtn:
                    AlarmActivity.this.finish();
                    break;
                case R.id.addBtn:
                    Intent intent = new Intent(AlarmActivity.this, AddAlarmActivity.class);
                    AlarmActivity.this.startActivity(intent);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        getData();
        super.onResume();
    }

    /**
     * 获取所有的设备
     */
    private void getData() {
        AlarmEntity.getList(AlarmActivity.this, new HttpCallback() {
            @Override
            public void onStart() {
                CommUtil.showProcessing(listView, true, true);
            }

            @Override
            public void onFinish() {
                CommUtil.hideProcessing();
            }

            @Override
            public void onSuccess(ResponseData obj) {
                if (obj.getRetcode() == 1) {
                    entityList.clear();
                    for (int i = 0; i < obj.getBodyArray().length(); i++) {
                        AlarmEntity device = new AlarmEntity(JSONHelper.getJSONObject(obj.getBodyArray(), i));
                        entityList.add(device);
                    }
                    if (entityList.size() != 0) {
                        listView.setVisibility(View.VISIBLE);
                        alarmPrompt.setVisibility(View.GONE);
                    } else {
                        listView.setVisibility(View.GONE);
                        alarmPrompt.setVisibility(View.VISIBLE);
                    }
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(AlarmActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String message) {
                Toast.makeText(AlarmActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
